package com.test;

import java.util.Scanner;

public class PrimeNumberApp {

    public static void main(String[] args) {
        PrimeNumberApp primeNumberApp = new PrimeNumberApp();
        primeNumberApp.execute();
    }

    public void execute() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入：");
        long number = scanner.nextLong();
        System.out.println("输入了：" + number);

        while (number != 0) {
            int threads = 4;
            long chunkSize = number / threads;
            PrimeCounter[] counters = new PrimeCounter[threads];
            Thread[] threadsArray = new Thread[threads];

            for (int i = 0; i < threads; i++) {
                long start = i * chunkSize + 2;
                long end = (i == threads - 1) ? number : start + chunkSize - 1;
                counters[i] = new PrimeCounter(start, end);
                threadsArray[i] = new Thread(counters[i]);
                threadsArray[i].start();
            }

            int count = 0;
            for (int i = 0; i < threads; i++) {
                try {
                    threadsArray[i].join();
                    count += counters[i].getCount();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("小于 " + number + " 的质数个数：" + count);

            System.out.println("请输入：");
            number = scanner.nextLong();
            System.out.println("输入了：" + number);
        }
    }

    public class PrimeCounter implements Runnable {
        private long start;
        private long end;
        private int count = 0;

        public PrimeCounter(long start, long end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public void run() {
            count = countPrimes(start, end);
        }

        public int getCount() {
            return count;
        }
    }

    public int countPrimes(long start, long end) {
        int count = 0;
        for (long i = start; i <= end; i++) {
            if (isPrime(i)) {
                count++;
            }
        }
        return count;
    }

    public boolean isPrime(long number) {
        if (number < 2) {
            return false;
        }

        long sqrNumber = (long) Math.sqrt(number);
        for (long i = 2; i <= sqrNumber; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}
